package com.uwantsoft.util;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;

import java.util.HashMap;

/**
 * @author Zhang Hui
 */
public class PerformanceChecker {

    private static ThreadLocal<PerformanceChecker> checkerThreadLocal = new ThreadLocal<PerformanceChecker>();
    private static Logger logger = Logger.getLogger(PerformanceChecker.class);
    private DateTime creationTime = new DateTime();
    private DateTime lastTime = new DateTime();
    private HashMap<String, DateTime> map = new HashMap<String, DateTime>();
    private boolean logEnable = true;

    private PerformanceChecker() {

    }

    public static void start(String log) {
        start(log, false);
    }

    public static void start(String log, boolean show) {
        PerformanceChecker checker = checker();
        checker.lastTime = new DateTime();
        checker.map.put(log, checker.lastTime);
        if (show) {
            if (checker.logEnable) {
                logger.info(Thread.currentThread().getId()+"[" + log + "][Start]");
            }
        }
    }

    public static void end(String log) {
        PerformanceChecker checker = checker();
        checker.lastTime = new DateTime();
        DateTime startTime = checker.map.get(log);
        Period period = new Period(startTime, checker.lastTime, PeriodType.millis());
        if (checker.logEnable) {
            logger.info(Thread.currentThread().getId()+"["+log+"][End]:" + period.getMillis());
        }
    }

    private long lastStep() {
        Period period = new Period(lastTime, JodaUtils.now(), PeriodType.millis());
        return period.getMillis();
    }

    private long totalTime() {
        Period period = new Period(creationTime, JodaUtils.now(), PeriodType.millis());
        return period.getMillis();
    }



    private static PerformanceChecker checker() {
        PerformanceChecker checker = checkerThreadLocal.get();
        if (checker == null) {
            checkerThreadLocal.set(new PerformanceChecker());
        }
        return checkerThreadLocal.get();
    }


    public static void turnOffLog() {
        checker().logEnable = false;
    }

    public static void turnOnLog() {
        checker().logEnable = true;
    }
}
